const DEFAULT_DURATION = 200
const DEFAULT_INTERVAL = 32

/**
 * 反复重绘的动画帮助类
 */
export default class {
    constructor(interval, duration) {
        this.interval = interval || DEFAULT_INTERVAL
        this.duration = duration || DEFAULT_DURATION

        this.startTime = 0
        this.finished = true
    }

    /**
     * 计算动画是否结束
     * @param running 未结束时的回调
     * @param finished 已完成时的回调
     */
    compute(running, finished) {
        if (this.finished) return false

        const timePassed = this.getTime() - this.startTime

        if (timePassed < this.duration) {
            const t = timePassed / this.duration
            running(t)
        } else {
            finished()
            this.finish()
        }

        return true
    }

    /**
     * 运行动画
     * @param compute 计算回调
     * @param run 每一帧动画的回调
     */
    run(compute, run) {
        const t = this.interval

        const runnable = () => {
            const hasNext = compute()
            run()
            if (hasNext) setTimeout(runnable, t)
        }
        setTimeout(runnable, t)
    }

    getTime() {
        return new Date().getTime()
    }

    /**
     * 开始动画，在run函数之前调用
     * @param duration 动画持续时间
     */
    start(duration) {
        this.startTime = this.getTime()
        this.finished = false
        if (duration) this.duration = duration
    }

    /**
     * 结束动画
     */
    finish() {
        this.finished = true
    }
}